package com.example.newinfinity.View.DrawView

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.example.newinfinity.IconModel.IconModelType
import com.example.newinfinity.IconModel.IconState
import com.example.newinfinity.MyViewModel.DrawViewModel
import com.example.newinfinity.View.Layer.LayerManager

class DrawView(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
    private val layerManager: LayerManager by lazy { //懒加载 防止DrawViewModel还未初始化 就获取其实例
        DrawViewModel.getDrawViewModel().layerManager
    }

    //添加图片背景时，设定rectF区域，使得图片完整显示在recyclerView的item上
    val imageRectF = RectF()

    //保存HomeFragment传递过来的当前绘制操作
    private var currentOperation = IconModelType.NONE

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //创建默认的图层
        layerManager.addLayer(measuredWidth, measuredHeight)

        imageRectF.apply {
            this.top = 0f
            this.left = 0f
            this.right = measuredWidth.toFloat()
            this.bottom = measuredHeight.toFloat()
        }
    }

    //将所有的图形bitmap与背景bitmap绘制到一个bitmap上 用于下载到本地相册中
    fun getAllBitmap(): Bitmap {
        val bitmaps = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)
        val mCanvas = Canvas(bitmaps)
        if (bgBitmap == null){
            val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
                this.color = Color.WHITE
            }
            //没有选择背景图片的话,默认的背景颜色为白色
            mCanvas.drawRect(0f,0f,width.toFloat(),height.toFloat(),paint)
        }
        if (bgBitmap != null) {
            mCanvas.drawBitmap(bgBitmap!!, null,imageRectF,null)
        }
        layerManager.getBitmaps().forEach { bitmap ->
            mCanvas.drawBitmap(bitmap, 0f, 0f, null)
        }
        return bitmaps
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //若选中了背景图片 需在底部绘制背景图片的bitmap
        if (bgBitmap != null) {
            canvas.drawBitmap(bgBitmap!!, null,imageRectF,null)
        }
        layerManager.draw()  //绘制所有图层到mBitmap上
        //获取所有图层的mBitmap 将其内容重新绘制到DrawView的画板上显示出来
        layerManager.getBitmaps().forEach { bitmap ->
            canvas.drawBitmap(bitmap, 0f, 0f, null)
        }
    }

    //保存传入的背景图片资源id
    private var bgBitmap: Bitmap? = null

    //接收HomeFragment中传入的背景图片资源id
    fun getBgBitmap(bitmap: Bitmap) {
        bgBitmap = bitmap
        invalidate() //刷新视图
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                when (currentOperation) {
                    IconModelType.DRAW_CIRCLE -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_RECTANGLE -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_LINE -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_CURVE -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_TRIANGLE -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_BEZIER -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_LINE_ARROW -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_ERASER -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_LOCATION -> {
                        layerManager.addShape(currentOperation, event.x, event.y)
                    }

                    IconModelType.DRAW_BRUSH -> {
                        //即使点击油漆桶时不要绘制图形 也应创建该类 防止在选中油漆桶时还可以绘制上一个选中的图形（mShapes中最新的shape还是上一个图形）
                        layerManager.fillColor(event.x, event.y)
                        invalidate()
                    }

                    IconModelType.DRAW_MOVE -> {  //选中移动功能
                        layerManager.changeIconSelectedState(event.x, event.y)
                        invalidate()
                    }

                    else -> {}
                }
            }

            MotionEvent.ACTION_MOVE -> {
                when (currentOperation) {
                    IconModelType.DRAW_CIRCLE -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_RECTANGLE -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_LINE -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_CURVE -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_TRIANGLE -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_BEZIER -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_LINE_ARROW -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_ERASER -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_LOCATION -> {
                        layerManager.addEndPoint(event.x, event.y)
                    }

                    IconModelType.DRAW_MOVE -> {
                        //传入二次点击时 开始移动的实时坐标
                        layerManager.getMoveDistance(event.x, event.y)
                    }

                    else -> {}
                }
                invalidate()
            }

            MotionEvent.ACTION_UP -> {
                if (currentOperation == IconModelType.DRAW_ERASER) {
                    //专门提供给橡皮擦显示矩形的显示状态清空方法 DrawView中手up矩形显示及消失
                    layerManager.changeEraserRectShowState()
                    //刷新重绘橡皮擦状态即修改为NORMAL 无法再绘制显示上去
                    invalidate()
                }
            }
        }
        return true
    }

    //接收HomeFragment传递的当前绘制操作
    fun setCurrentOperation(operation: IconModelType, selectState: IconState) {
        //只有当前点击的icon选中状态为selected才保存绘制类型并进行绘制
        currentOperation = if (selectState == IconState.SELECTED) {
            when (operation) {
                IconModelType.DRAW_MENU -> {
                    IconModelType.NONE
                }

                else -> operation
            }
        } else {
            //图形icon未被选中
            IconModelType.NONE
        }
    }

    //提供给外部 用于刷新视图 获得最新的图案显示
    fun refreshLayer() {
        invalidate()
    }

    //点击每一个icon图标时 若界面中有移动move的选中图形需要将currentSelectedShape清空并修改其选中状态为MoveType.NONE
    fun clearMoveShape() {
        layerManager.clearMoveShape()
        invalidate()
    }
}